package cheme.ProcessModel.Interpreter.Parsers;

import cheme.Interpreter.Parser.Parser;
import syntaxtree.Node;

/*
 * Provides the basic functionality for all Parsers. The control flow is:
 * 
 * parse(text) -> 
 * 	prepareString(text), 	//Let derived classes preprocess the text string.
 * 							//Some will wrap the text in delimiters to prevent partial strings satisfying rules whre full strings are desired.
 * 
 * 	Parser.init(text), 		//this sets up the javaCC based parser with the text.
 * 
 * 	internalParse(). 		//Let the derived class call a specific Parser function to process the text.
 */
public abstract class AbstractParser implements IParser
{
	protected String parseMessage = "";
	protected String source = "";
	
	protected String getSource()
	{
		return source;
	}

	public String prepareString(String text)
	{
		return text.trim();
	}
	
	/*
	 * Initiates the specific parser function on the prepared text.
	 */
	protected abstract Node internalParse();
	
	protected final void Init(String text)
	{
		source = text.trim();
		Parser.init(source);
	}
	
	public final Node parse(String text)
	{
		Node result = null;
		String newText = prepareString(text);
		Init(newText);
		//Init(prepareString(text));
		
		try
		{
			result = internalParse();
		}
		catch(Error e)
		{
			parseMessage = e.getMessage();
		}
		
		return result;
	}
	
	
	public String getMessage()
	{
		return parseMessage;
	}
	
	protected void setParseMessage(String parseMessage)
	{
		this.parseMessage = parseMessage;
	}
}
